package com.vay.de.dang.online.ui.apply;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.util.VnUIManager;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.DialogMenuOption;
import com.vay.de.dang.online.view.VnItemLayout;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.entiy.EmergencyContactsEntity;
import com.vay.de.dang.online.entiy.EssentialContactsEntity;
import com.vay.de.dang.online.entiy.AppConfigEntity;
import com.vay.de.dang.online.entiy.IncomeRequestEntity;
import com.vay.de.dang.online.entiy.NormalContactsEntity;
import com.vay.de.dang.online.entiy.MenuItemEntity;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.util.CallerUtil;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.RequestHelper;
import com.vay.de.dang.online.util.VnHandler;
import com.vay.de.dang.online.databinding.ActivityStep1Binding;
import com.vay.de.dang.online.resp.RCodeTableDto;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.DeviceApi;
import com.vay.de.dang.online.web.TableApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.ui.WithBack1Activity;
import com.vay.de.dang.online.view.DialogAddress;

import java.util.ArrayList;
import java.util.List;

import cc.taylorzhang.singleclick.SingleClickUtil;

public class Step1Activity extends WithBack1Activity {

    private ActivityStep1Binding binding;
    private IncomeRequestEntity incomeRequest;
    private AppConfigEntity homeConfig;
    private EssentialContactsEntity essentialContacts;

    // 紧急联系人
    private List<View> emergencyContactsViews = new ArrayList<>();

    // 必要联系人
    private List<View> essentialContactsViews = new ArrayList<>();

    // 选择联系人
    private int selectType;
    private int selectIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStep1Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        incomeRequest = RequestHelper.currentIncome();
        homeConfig = VnContext.instance().getAppConfig();
        essentialContacts = homeConfig.getNumberNonEssentialContacts();

        // 业务埋点
        BaseApi.execBuriedPoint(4000, 4000, "完善资料-基础信息", "基础页面可见");

        findViewById(R.id.bnt_back_home).setOnClickListener(view -> {

            // 业务埋点
            BaseApi.execBuriedPoint(4010, 4000, "完善资料-基础信息", "基础资料页返回");

            finish();
        });

        SingleClickUtil.onSingleClick(findViewById(R.id.bnt_next), view -> {
            nextActivity();
        });

        // 关系
        TableApi.codeTable(TableApi.EMERGENCY_CONTACT_RELATIONSHIP, new ReqCallback() {
            @Override
            public void callback(ReqResult value) {

            }
        });

        loadView();

        // 规则
        BaseApi.baseInfoRule(new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<PropertyRuleEntity> list = (List<PropertyRuleEntity>) value.result;
                    if (VnUtil.isEmpty(list)) {
                        finish();
                    } else {
                        RequestHelper.setBaseRuleList(list);
                    }
                } else {
                    finish();
                }
            }
        });

        // 用户信息
        RequestHelper.queryCustomerData(mActivity, true, dto -> {

            // 基本信息
            RCodeTableDto p = dto.getResidentialAddressProvince();
            RCodeTableDto c = dto.getResidentialAddressCity();
            RCodeTableDto r = dto.getResidentialAddressArea();
            if (p != null && c != null && r != null) {
                binding.city.setContent(p.getLabel() + "-" + c.getLabel() + "-" + r.getLabel());
            }
            binding.fullAddress.setContent(dto.getResidentialAddress());

            // 居住时长
            RCodeTableDto tableDto = dto.getResidenceTimeLength();
            if (tableDto != null) {
                binding.yearsOfResidence.setContent(tableDto.getLabel());
                incomeRequest.setResidenceTimeLength(tableDto.getValue());
            }

            // 居住类型
            tableDto = dto.getResidentialType();
            if (tableDto != null) {
                binding.typeOfResidence.setContent(tableDto.getLabel());
                incomeRequest.setResidentialType(tableDto.getValue());
            }

            // 教育
            tableDto = dto.getHighestEducation();
            if (tableDto != null) {
                binding.education.setContent(tableDto.getLabel());
            }

            // 婚姻
            tableDto = dto.getMaritalStatus();
            if (tableDto != null) {
                binding.maritalStatus.setContent(tableDto.getLabel());
            }

            // 子女
            tableDto = dto.getChildrenNumber();
            if (tableDto != null) {
                binding.noChild.setContent(tableDto.getLabel());
            }

            // email
            binding.email.setContent(dto.getEmail());

            // facebook
            binding.facebook.setContent(dto.getFacebook());

            // Zalo
            binding.zalo.setContent(dto.getZaloId());

            // 必要联系人信息
            updateContracts();

            // 紧急联系人
            updateEmergencyContracts();
        });
    }

    private void loadView() {

        // 城市
        binding.city.setOnItemClick(() -> {
            new DialogAddress(mActivity)
                    .setOnCityClick((province, city, region) -> {
                        binding.city.setContent(province.getAddressName()
                                + "-" + city.getAddressName()
                                + "-" + region.getAddressName());
                        incomeRequest.setResidentialAddressProvince(province.getAddressCode());
                        incomeRequest.setResidentialAddressCity(city.getAddressCode());
                        incomeRequest.setResidentialAddressArea(region.getAddressCode());
                    }).showCity(mActivity);
        });

        // 居住地时间
        binding.yearsOfResidence.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        binding.yearsOfResidence.setContent(bean.getLabel());
                        incomeRequest.setResidenceTimeLength(bean.getValue());
                    })
                    .showChoice(getString(R.string.label_years_of_residence), TableApi.LIVE_YEARS);
        });

        // 居住类型
        binding.typeOfResidence.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        binding.typeOfResidence.setContent(bean.getLabel());
                        incomeRequest.setResidentialType(bean.getValue());
                    })
                    .showChoice(getString(R.string.label_type_of_residence), TableApi.LIVE_TYPE);
        });

        // 婚姻状态
        binding.maritalStatus.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {

                        binding.maritalStatus.setContent(bean.getLabel());
                        incomeRequest.setMaritalStatus(bean.getValue());
                    })
                    .showChoice(getString(R.string.label_marital_status), TableApi.MARITAL_STATUS);
        });

        // 子女数量
        binding.noChild.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {

                        binding.noChild.setContent(bean.getLabel());
                        incomeRequest.setChildrenNumber(bean.getValue());
                    })
                    .showChoice(getString(R.string.label_no_of_children), TableApi.NUMBER_OF_CHILDREN);
        });

        // 最高学历
        binding.education.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        binding.education.setContent(bean.getLabel());
                        incomeRequest.setHighestEducation(bean.getValue());
                    })
                    .showChoice(getString(R.string.label_education), TableApi.HIGHEST_EDUCATION);
        });

        // 紧急联系人
        updateEmergencyContracts();

        essentialContactsViews.clear();
        // 必要联系人
        if (essentialContacts != null) {
            updateContracts();
        }

        // 新增联系人
        binding.bntAddContracts.setOnClickListener(view -> {
            RequestHelper.essentialContactsList.add(new EmergencyContactsEntity());
            updateContracts();
        });
    }

    private void nextActivity() {

        // 城市
        if (!VnUtil.isDropList(binding.city, "City Not empty")) return;
        incomeRequest.setResidentialAddress(binding.city.getContent());

        // 详细地址
        if (!VnUtil.isRuleOk(binding.fullAddress,
                RequestHelper.findBaseRule("residentialAddress"))) return;
        incomeRequest.setRegisteredResidence(binding.fullAddress.getContent());

        // 居住时长
        if (!VnUtil.isDropList(binding.yearsOfResidence, "Not empty")) return;
        // 居住类型
        if (!VnUtil.isDropList(binding.typeOfResidence, "Not empty")) return;

        // 婚姻状态
        if (!VnUtil.isDropList(binding.maritalStatus, "Not empty")) return;
        // 小孩数量
        if (!VnUtil.isDropList(binding.noChild, "Not empty")) return;
        // 最高学历
        if (!VnUtil.isDropList(binding.education, "Not empty")) return;

        // email
        if (!VnUtil.isRuleOk(binding.email,
                RequestHelper.findBaseRule("email"))) return;
        incomeRequest.setEmail(binding.email.getContent());

        String facebookId = binding.facebook.getContent();
        String zaloId = binding.zalo.getContent();

        // 必须保证存在一个
        if (TextUtils.isEmpty(facebookId) && TextUtils.isEmpty(zaloId)) {
            showHint("Facebook or Zalo is empty");
            return;
        }

        incomeRequest.setFacebook(facebookId);
        incomeRequest.setZaloId(zaloId);

        // 紧急联系人
        List<EmergencyContactsEntity> emergencyContacts = RequestHelper.emergencyContactsList;
        int countNumber = 0;
        for (int i = 0; i < emergencyContactsViews.size(); i++) {

            View iv = emergencyContactsViews.get(i);
            EmergencyContactsEntity ec = null;
            if (i < emergencyContacts.size()) {
                ec = emergencyContacts.get(i);
            }

            VnItemLayout relation = iv.findViewById(R.id.item_relationship);
            VnItemLayout phone = iv.findViewById(R.id.item_phone);
            VnItemLayout name = iv.findViewById(R.id.item_name);

            if (ec == null) {
                phone.showWarring("Not empty");
                return;
            } else {
                if (VnUtil.isEmpty(ec.getContactRelation())) {
                    relation.showWarring("Not empty");
                    return;
                }

                String sName = name.getContent();
                if (VnUtil.isEmpty(sName)) {
                    name.showWarring("Not empty");
                    return;
                }

                ec.setContactRealName(sName);
                countNumber++;
            }
        }

        if (countNumber != homeConfig.getNumberOfEmergencyContacts()) {
            showHint(R.string.error_emergency_number);
            return;
        }

        if (!checkEmergencyContract()) {
            showHint(R.string.error_emergency_contract);
            return;
        }

        // 业务埋点
        BaseApi.execBuriedPoint(4099, 4000,
                "完善资料-基础信息", "基础资料下一步");

        // 上传资料
        DeviceApi.uploadCustomerData(1, null,
                null, null, null,
                new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            VnUIManager.nextActivity(mActivity, Step2Activity.class);
                        }
                    }
                }.showDialog(true));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (data == null) return;

        // 选择联系人
        if (requestCode == 2001) {
            String[] str = CallerUtil.readContacts(mActivity, data.getData());
            if (str == null || str.length < 3) return;

            String phone = str[1];
            String name = str[0];
            String strTime = str[2];

            // 去除中间空格
            if (phone != null) {
                phone = phone.trim().replace(" ", "");
                //if (phone.length() > 10) phone = phone.substring(0, 10);
            }

            String error = RequestHelper.checkContactsPhone(phone);
            if (error != null) {
                showHint(error);
                return;
            }

            error = RequestHelper.checkPhoneRepeat(phone);
            if (error != null) {
                showHint(error);
                return;
            }

            long modifyTime = 0;
            try {
                modifyTime = Long.parseLong(strTime);
            } catch (Exception e) {
                e.printStackTrace();
            }

            selectContacts(name, phone, modifyTime);
        }
    }

    // 必要联系人
    private void updateContracts() {
        List<EmergencyContactsEntity> contacts = RequestHelper.essentialContactsList;
        LayoutInflater inflater = getLayoutInflater();
        int size = contacts.size();
        essentialContactsViews.clear();
        binding.essentialLayout.removeAllViews();
        for (int index = 0; index < size; index++) {

            EmergencyContactsEntity ecBean = contacts.get(index);
            final int targetIndex = index;
            View iv = inflater.inflate(R.layout.view_contacts, null);

            ImageView bntDel = iv.findViewById(R.id.bnt_delete);
            TextView tvLabel = iv.findViewById(R.id.tv_label);
            View bntSelect = iv.findViewById(R.id.bnt_select);
            VnItemLayout relation = iv.findViewById(R.id.item_relationship);
            VnItemLayout phone = iv.findViewById(R.id.item_phone);
            VnItemLayout name = iv.findViewById(R.id.item_name);

            tvLabel.setText("* " + getString(R.string.per_contract_label) + " " + (index + 1));
            relation.setContent(findRelationship(ecBean.getContactRelation()));
            phone.setContent(ecBean.getContactPhone());
            name.setContent(ecBean.getContactRealName());

            // 打开通讯录
            bntSelect.setOnClickListener(v -> {
                selectType = 2;
                selectIndex = targetIndex;
                CallerUtil.choiceContract(mActivity, 2001);
            });

            // 关系
            relation.setOnItemClick(() -> {
                new DialogMenuOption(mActivity)
                        .setOnOptionItemClick(bean -> {
                            relation.setContent(bean.getLabel());
                            ecBean.setContactRelation(bean.getValue());
                        })
                        .showChoice(getString(R.string.label_relationship), TableApi.EMERGENCY_CONTACT_RELATIONSHIP);
            });

            bntDel.setVisibility(View.VISIBLE);
            bntDel.setOnClickListener(v -> {
                contacts.remove(ecBean);
                updateContracts();
            });

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.topMargin = index > 0 ? VnApp.getDimension(R.dimen.x12) : 0;

            binding.essentialLayout.addView(iv, lp);
            essentialContactsViews.add(iv);
        }

        updateTips();
    }

    // 紧急联系人
    private void updateEmergencyContracts() {
        List<EmergencyContactsEntity> contacts = RequestHelper.emergencyContactsList;
        int number = homeConfig.getNumberOfEmergencyContacts();
        LayoutInflater inflater = getLayoutInflater();
        binding.emergencyLayout.removeAllViews();
        emergencyContactsViews.clear();

        for (int index = 0; index < number; index++) {

            EmergencyContactsEntity ecBean = contacts.get(index);
            final int targetIndex = index;

            View iv = inflater.inflate(R.layout.view_contacts, null);
            TextView tvLabel = iv.findViewById(R.id.tv_label);
            View bntSelect = iv.findViewById(R.id.bnt_select);
            VnItemLayout relation = iv.findViewById(R.id.item_relationship);
            VnItemLayout phone = iv.findViewById(R.id.item_phone);
            VnItemLayout name = iv.findViewById(R.id.item_name);

            tvLabel.setText("* " + getString(R.string.title_emergency_contract) + " " + (index + 1));
            relation.setContent(findRelationship(ecBean.getContactRelation()));
            phone.setContent(ecBean.getContactPhone());
            name.setContent(ecBean.getContactRealName());

            // 打开通讯录
            bntSelect.setOnClickListener(v -> {
                selectType = 1;
                selectIndex = targetIndex;
                CallerUtil.choiceContract(mActivity, 2001);
            });

            // 关系
            relation.setOnItemClick(() -> {
                new DialogMenuOption(mActivity)
                        .setOnOptionItemClick(bean -> {
                            relation.setContent(bean.getLabel());
                            ecBean.setContactRelation(bean.getValue());
                        })
                        .showChoice(getString(R.string.label_relationship), TableApi.EMERGENCY_CONTACT_RELATIONSHIP);
            });

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.topMargin = index > 0 ? VnApp.getDimension(R.dimen.x12) : 0;
            binding.emergencyLayout.addView(iv, lp);
            emergencyContactsViews.add(iv);
        }
    }

    private boolean checkEmergencyContract() {
        List<EmergencyContactsEntity> emergencyContacts = RequestHelper.emergencyContactsList;
        for (EmergencyContactsEntity ec : emergencyContacts) {
            String phone = ec != null ? ec.getContactPhone() : "";
            for (EmergencyContactsEntity oo : emergencyContacts) {
                String p2 = oo != null ? oo.getContactPhone() : "";
                if (phone.equals(p2)) return true;
            }
        }
        return false;
    }

    private void selectContacts(String name, String phone, long modifyTime) {

        // 联系人是否重复
        if (checkPhone(RequestHelper.emergencyContactsList, phone)) {
            showHint(R.string.error_emergency_contract);
            return;
        }
        if (checkPhone(RequestHelper.essentialContactsList, phone)) {
            showHint(R.string.error_emergency_contract);
            return;
        }

        if (selectType == 1) {
            EmergencyContactsEntity bean = RequestHelper.emergencyContactsList.get(selectIndex);
            bean.setContactPhone(phone);
            bean.setContactName(name);
            bean.setContactRealName(name);
            updateViewInfo(emergencyContactsViews.get(selectIndex), bean);
        } else {
            EmergencyContactsEntity bean = RequestHelper.essentialContactsList.get(selectIndex);
            bean.setContactPhone(phone);
            bean.setContactName(name);
            bean.setContactRealName(name);
            updateViewInfo(essentialContactsViews.get(selectIndex), bean);
        }

        // 上传到通信录
        NormalContactsEntity bean = new NormalContactsEntity();
        bean.setAddressBookId("0");
        bean.setLinkPhone(phone);
        bean.setLinkName(name);
        bean.setSourceType("");
        bean.setSaveTime(modifyTime);
        bean.setLastTime(modifyTime);
        DeviceApi.uploadAddressBook(bean, new ReqCallback() {
            @Override
            public void callback(ReqResult value) {

            }
        });
    }

    private void updateViewInfo(View iv, EmergencyContactsEntity bean) {
        //VnItemLayout relation = iv.findViewById(R.id.item_relationship);
        VnItemLayout phone = iv.findViewById(R.id.item_phone);
        VnItemLayout name = iv.findViewById(R.id.item_name);
        phone.setContent(bean.getContactPhone());
        name.setContent(bean.getContactRealName());
    }

    private boolean checkPhone(List<EmergencyContactsEntity> list, String phone) {
        for (EmergencyContactsEntity bean : list) {
            if (!TextUtils.isEmpty(bean.getContactPhone())
                    && bean.getContactPhone().equals(phone)) {
                return true;
            }
        }
        return false;
    }

    private void updateTips() {
        VnHandler.runUIDelayed(() -> {

            List<String> message = essentialContacts.getMessage();
            List<EmergencyContactsEntity> contacts = RequestHelper.essentialContactsList;
            int count = 0;
            for (EmergencyContactsEntity bean : contacts) {
                if (!VnUtil.isEmpty(bean.getContactPhone())) {
                    count++;
                }
            }

            if (count > 0) {
                if (count >= 4) binding.tvTips.setText("Tips: " + message.get(message.size() - 1));
                else binding.tvTips.setText("Tips: " + message.get(count - 1));
            } else {
                binding.tvTips.setText("Mẹo：Thêm nhiều liên hệ hơn để nhận được tín dụng cao hơn nhanh hơn");
            }
        }, 200);
    }

    private String findRelationship(String value) {
        List<MenuItemEntity> list = TableApi.getCodeTable(TableApi.EMERGENCY_CONTACT_RELATIONSHIP);
        if (!VnUtil.isEmpty(list) && value != null) {
            for (MenuItemEntity item : list) {
                if (item.getValue().equals(value))
                    return item.getLabel();
            }
        }
        return "";
    }

}
